package com.zzy.service;

import com.zzy.dao.TokenDao;
import com.zzy.dao.UserDao;
import model.Token;
import model.User;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * @Author: zhangzhenyu
 * @Date: 2021/1/20
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;
    @Reference
    private CodeService codeService;
    @Override
    public int register(String email, String password, String code) {

        int validate = codeService.validate(email, code);
        if (validate==0){
            User user=new User();
            user.setEmail(email);
            user.setPassword(password);
            user.setCreatetime(new Date());
            userDao.saveAndFlush(user);
        }
            return validate;

    }

    @Override
    public Boolean isRegistered(String email) {

        User resume = new User();
        resume.setEmail(email);
        Example<User> example = Example.of(resume);
        return userDao.findAll(example).size()>0;
    }

    @Override
    public String login(HttpServletResponse response, String email, String password) {
        User resume = new User();
        resume.setEmail(email);
        resume.setPassword(password);
        Example<User> example = Example.of(resume);
        if (userDao.findAll(example).size()>0){
            String tokenStr = UUID.randomUUID().toString();
            Token token=new Token();
            token.setEmail(email);
            token.setToken(tokenStr);
            tokenDao.saveAndFlush(token);
            Cookie cookie=new Cookie("token",tokenStr);
            response.addCookie(cookie);
            return tokenStr;
        }else {
            return "false";
        }




    }

    @Override
    public String info(String token) {
        Token token1 = new Token();
        token1.setToken(token);
        Example<Token> example = Example.of(token1);
        List<Token> all = tokenDao.findAll(example);
        if (all.size()>0){
            return all.get(0).getEmail();
        }
        return "null";
    }
}
